package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.YddLinkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("ydd_link")
@Slf4j
public class YddLinkController {

    @Autowired
    private YddLinkService yddLinkService;

    /**
     * 查看链接详情
     *
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id) {
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddLink::getId, Integer.parseInt(id));

        YddLink one = yddLinkService.getOne(queryWrapper);
        if (one != null) {
            return ResultData.ok("查询详情成功", one);
        }
        return ResultData.error("查询详情失败");
    }

    /**
     * 修改链接信息
     *
     * @param yddLink
     * @return
     */
    @PostMapping("update")
    public ResultData update(@RequestBody YddLink yddLink) {
        if (yddLink != null) {
            boolean b = yddLinkService.updateById(yddLink);
            return ResultData.ok("修改成功", yddLink);
        }
        return ResultData.error("修改失败");
    }

    /**
     * 删除链接信息
     *
     * @param id
     * @return
     */
    @GetMapping("del")
    public ResultData delete(String id) {
        if (StringUtils.isNotEmpty(id)) {
            long longId = Long.parseLong(id);

            boolean b = yddLinkService.removeById(longId);
            if (b) {
                return ResultData.ok("删除成功", null);
            }
        }
        return ResultData.error("删除失败");
    }

    /**
     * 链接分页列表显示
     *
     * @param type  类型，1是文字类型，2图片类型
     * @param page  页码数
     * @param limit 每页数量
     * @return
     */
    @GetMapping("list")
    public ResultData pageList(String type, String page, String limit) {

        long currentPage = Long.parseLong(page);
        long pageSize = Long.parseLong(limit);

        Page<YddLink> yddLinkPage = new Page<YddLink>(currentPage, pageSize);
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(type), YddLink::getType, type);

        yddLinkService.page(yddLinkPage, queryWrapper);

        return ResultData.ok("分页查询成功", PageResult.getPage(yddLinkPage));
    }

    @PostMapping("add")
    public ResultData add(@RequestBody YddLink yddLink) {

        boolean save = yddLinkService.save(yddLink);
        if (save) {
            return ResultData.ok("添加成功", yddLink);
        }
        return ResultData.error("添加失败");
    }

}

